package bitetorrent.helper;

import bitetorrent.Torrent;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

/**
 *
 * @author Robert Gunawan
 */
public class Request {

    public static String makeGetRequest(Torrent torrent, String event, int port, int uploaded, int downloaded) {
        String hasil = "";
        int sisa = torrent.fileLength - downloaded;

        hasil = "info_hash=" + torrent.fileName + "&port=" + port + "&uploaded=" + uploaded + "&downloaded=" + downloaded + "&left=" + sisa;
        if (event != null) {
            hasil += "&event=" + event;
        }
        return hasil;
    }

    public static String sendGetRequest(String endpoint, String requestParameters) {
        String result = null;

        if (endpoint.startsWith("http://")) {
            // Send a GET request to the servlet
            try {
                // Construct data
                StringBuilder data = new StringBuilder();

                // Send data
                String urlStr = endpoint;
                if (requestParameters != null && requestParameters.length() > 0) {
                    urlStr += "?" + requestParameters;
                }
                URL url = new URL(urlStr);
                URLConnection conn = url.openConnection();

                // Get the response
                BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = rd.readLine()) != null) {
                    sb.append(line);
                }
                rd.close();
                result = sb.toString();
            } catch (Exception e) {
            }
        }

        return result;
    }
}
